//
//  RJCheckBottomModel.m
//  AirQuality
//
//  Created by Po on 15/3/24.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCheckBottomModel.h"
#import "RJTools.h"
@interface RJCheckBottomModel ()

@property (assign, nonatomic) BOOL needRequest;             //是否需要请求
@property (strong, nonatomic) NSDictionary * dataDic;

- (void)initEvent;
@end

@implementation RJCheckBottomModel

#pragma mark - user-defined initialization function
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initEvent];
    }
    return self;
}

- (void)initEvent
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCityAirData) name:@"updateCityAirData" object:nil];
}


- (void)setSrcData:(NSArray *)data
{
    _data = [NSMutableArray arrayWithArray:data];
    [self updateData];
}

/**根据当前数据刷新数据*/
- (void)updateData
{
    _needRequest = NO;
    _shutDownNet = YES;
    [self getPositionData];
}

- (void)setKeyString:(NSString *)keyString
{
    if ([_keyString isEqualToString:keyString] || !_keyString) {
        _needRequest = YES;
        _keyString = keyString;
    } else {
        _keyString = keyString;
        _needRequest = NO;
//        [self updateAllAirValue];
    }
}

///**传入对应城市数据*/
- (void)getPositionData
{
    NSUInteger citycode;
    NSMutableArray * stationData = [NSMutableArray array];
    if (![RJUserData defaultRJUserData].isProvince) {
        if (_data.count == 0) {
            return;
        }
        NSUserDefaults * userId = [NSUserDefaults standardUserDefaults];
        NSArray * userIdArr = [userId objectForKey:@"userId1"];
        NSString * userId1 = userIdArr[0];
        NSString * userCityCode = userIdArr[1];
        NSDictionary * dic = [NSDictionary dictionary];
        for (NSDictionary * dic1 in _data) {
          NSString * citycode = [NSString stringWithFormat:@"%@",dic1[@"CITYCODE"]];
            if ([citycode isEqualToString:userCityCode]) {
                dic = dic1;
                _dataDic = dic;
                break;
            }
        }
        citycode = [dic[@"CITYCODE"] integerValue];
        NSArray * arr = dic[@"STATIONTYPES"];
        for (NSInteger i = 0; i < arr.count ; i ++) {
            [stationData addObject:dic[@"STATIONTYPES"][i][@"STATIONS"]];
        }
        NSArray * arr1 = stationData[0];
        NSMutableArray * arr2 = [NSMutableArray arrayWithArray:arr1];
        if (stationData.count > 1) {
            [arr2 addObject:stationData[1][0]];
        }
        stationData = [NSMutableArray arrayWithArray:arr2];
    } else {
        citycode = [[[_data[0] objectForKey:@"STATIONS"][0] objectForKey:@"CITYCODE"] integerValue];
        stationData = _data;
    }
    
    //判断是否需要重新设值
    if ([_cityCode integerValue] != citycode) {
        _needRequest = YES;
        [_positionData removeAllObjects];
        _positionData = [[NSMutableArray alloc] init];
        for (NSUInteger i = 0; i < _data.count; i ++) {
            if (![RJUserData defaultRJUserData].isProvince) {
                [_positionData addObjectsFromArray:stationData];
                break;
            } else {
                for (NSDictionary * dic in [stationData[i] objectForKey:@"STATIONS"]) {
                    if ([dic[@"STATIONTYPEID"] integerValue] == 4) {
                        continue;
                    }
                    [_positionData addObject:dic];
                }
            }
        }
        //根据站点长度初始化对应空气数组长度
        [self updateAllAirValue];
    }
}

/**获取所有站点污染数值*/
- (void)updateAllAirValue
{
    [_valueData removeAllObjects];
    _valueData = [[NSMutableArray alloc] initWithArray:_positionData];
    
    NSMutableArray * positionCodes = [NSMutableArray array];                //所有站点Code
    for (NSUInteger i = 0; i < _positionData.count; i ++) {
        NSString * stationCode;
        if ([RJUserData defaultRJUserData].isProvince) {
            stationCode = [_positionData[i] objectForKey:@"STATIONCODE"];
        } else {
            stationCode = [_positionData[i] objectForKey:@"STATIONCODE"];
        }
        if ([stationCode rangeOfString:@"C"].location != NSNotFound) {
            continue;
        }
        [positionCodes addObject:[NSString stringWithFormat:@"'%@'",stationCode]];
    }
    if (![RJUserData defaultRJUserData].isProvince) {
        NSDictionary * dic = _dataDic;
        positionCodes = [NSMutableArray array];
        NSArray * array = dic[@"STATIONTYPES"];
        for (NSDictionary * dictionArray in array) {
            NSArray * cityArr = dictionArray[@"STATIONS"];
            for(NSDictionary * cityDic in cityArr) {
                [positionCodes addObject:[NSString stringWithFormat:@"'%@'",cityDic[@"STATIONCODE"]]];
            }
        }
    }
    NSString * stationCodes = [positionCodes componentsJoinedByString:@","];
//    stationCodes = @"'1001A'";
    NSString * time = [RJTools getTimeWithFormat:@"yyyy-MM-dd" time:YesterdayDate];
    //http://xsscd.xicp.net:5100
    NSUserDefaults * userId = [NSUserDefaults standardUserDefaults];
    NSArray * userIdArr = [userId objectForKey:@"userId1"];
    NSString * userId1 = userIdArr[0];
    NSString * userCityCode = userIdArr[1];
    //@"http://newair.scemc.cn:5100/smartadmin/statAnalyse/getDayDataForApp" @"http://xsscd.xicp.net:5100%@" 
    [RJNetWork myNetRequestWithAddress:@"http://www.scnewair.cn:3389/smartadmin/statAnalyse/getDayDataForApp" data:@{@"type":@"4",@"area":stationCodes,@"starttime":time,@"endtime":time,@"gaslist":@"SO2,NO2,O3,PM10,PM2.5,AQI,CO",@"userId":userId1,@"cityCode":userCityCode} completeBlock:^(id responseObject) {
        //取出数据并排序 AQI,PM2.5,PM10,O3,SO2,NO2,CO
        NSDictionary * data = responseObject[@"data"];
        NSMutableDictionary * tempDic = [NSMutableDictionary dictionary];
        for (NSArray * array in [data allValues]) {
            NSDictionary * stationData = [array lastObject];
            [tempDic setObject:stationData forKey:stationData[@"STATIONCODE"]];
        }
        
        //根据站点顺序重新排序
        NSMutableArray * tempArray = [NSMutableArray array];
        for (NSDictionary * positionData in _positionData) {
            NSString * key = positionData[@"STATIONCODE"];
            if (tempDic[key]) {
                [tempArray addObject:tempDic[key]];
            }
        }
        _allAirData = [NSMutableArray arrayWithArray:tempArray];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PositionValueIsGet" object:@{@"result":@"1"}];
    }failBlack:^(id response) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PositionValueIsGet" object:@{@"result":@"0"}];
    }];
}

- (void)freeSelf
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateCityAirData" object:nil];
}

#pragma mark - Notifaction
- (void)updateCityAirData
{
    [self updateData];
}
@end
